import axios from 'axios'
import { ElMessage } from 'element-plus'
import type { AxiosError } from 'axios'
import { useStore } from '@/stores'
import { useUserStore } from '@/stores'

const env = import.meta.env

const instance = axios.create({
  baseURL: env.VITE_API_BASE_URL,
  timeout: env.VITE_API_TIMEOUT
})

instance.interceptors.request.use((config) => {
  const userStore = useUserStore()
  const token = userStore.token

  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`
  }

  return config
})
instance.interceptors.response.use(
  (response) => {
    // const { headers, data } = response
    // if (headers['content-type'].indexOf('application/json') === -1) {
    //   // 如果不是 json 格式的数据，直接返回原始响应数据进行处理
    //   return data
    // }

    const { data } = response

    if (!data) {
      ElMessage.error(`网络错误：数据为空`)
      return
    }

    if (!data.status) {
      if ([-1, -2, -3].includes(data.code)) {
        // 用户失效、登录异常
        const store = useStore()
        store.command = 'TokenExpired'
        store.lastMessage = data.message
        return
      }
      ElMessage.error(data.message)
    }

    return data
  },
  (error: AxiosError) => {
    // error === throw AxiosError(code, config, message, name, request, response, stack)
    const { message } = error

    ElMessage.error(`网络错误：${message}`)

    const status = error.response?.status
    if (status === 401) {
      // Unauthorized 无效凭证，无法继续保持登录，需要清除当前用户状态，让用户重新登录
      ElMessage.error(`网络错误：${message}`)
      // router.replace({ name: ROUTER_LOGIN_NAME })
    } else if (status === 500) {
      ElMessage.error(`网络错误：服务错误，请联系管理员重启服务`)
    }

    // 处理响应错误
    return Promise.reject(error)
  }
)

export default instance
